package com.byeonely.android.gcm.demo.app;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDBHelper extends SQLiteOpenHelper {

	// Database Version
    private static final int DATABASE_VERSION = 1;
 
    // Database Name
    private static final String DATABASE_NAME = "sblm";
	
	// Contacts Table name
	private static final String TABLE_NAME = "contacts";

	// Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    
	public MyDBHelper(Context context) {
//		super(context, name, factory, version);
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + KEY_ID + " INTEGER PRIMARY KEY," 
				+ KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" 
				+ ")";
//		db.beginTransaction();
        db.execSQL(CREATE_CONTACTS_TABLE);
//        db.setTransactionSuccessful();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String DROP_CONTACTS_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
//		db.beginTransaction();
        db.execSQL(DROP_CONTACTS_TABLE);
//        db.setTransactionSuccessful();
        onCreate(db);
	}

	public void addContact(Contact contact) {
		SQLiteDatabase db = getReadableDatabase();
		ContentValues values = new ContentValues();
		values.put(KEY_NAME, contact.getName());
		values.put(KEY_PH_NO, contact.getPhoneNumber());
		db.insert(TABLE_NAME, null, values);
	}
	
	public Contact getContact(int id) {
		SQLiteDatabase db = getReadableDatabase();
		String selection = KEY_ID + "=?";
		Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_PH_NO}, selection, 
				new String[]{String.valueOf(id)}, null, null, null);
		if (cursor != null) {
			cursor.moveToFirst();
		}
		Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2));
		return contact;
	}
	
	public Contact getContact(String name) {
		SQLiteDatabase db = getReadableDatabase();
		String selection = KEY_NAME + "=?";
		Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_PH_NO}, selection, 
				new String[]{name}, null, null, null);
		if (cursor != null) {
			cursor.moveToFirst();
		}
		Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2));
		return contact;
	}
	
}
